package drds.global_transaction.transaction_coordinator;

import drds.common.Constants;
import drds.global_transaction.api.rpc.rpc_server.RpcServer;
import drds.global_transaction.common.GlobalTransactionIds;
import drds.global_transaction.common.util.Nets;
import drds.global_transaction.transaction_coordinator.transaction_coordinator.TransactionCoordinator;
import drds.global_transaction.transaction_coordinator.transaction_session.TransactionSessionManagerFactory;

import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Server
{

	private static final ThreadPoolExecutor WORKING_THREADS = new ThreadPoolExecutor(//
			100, //
			500, //
			500, //
			TimeUnit.SECONDS, //
			new LinkedBlockingQueue<Runnable>(20000), new ThreadPoolExecutor.CallerRunsPolicy());

	public static void main(String[] args) throws IOException
	{
		Constants.developMode = true;
		RpcServer rpcServer = new RpcServer(WORKING_THREADS);

		if (args.length > 0)
		{
			int port = Integer.parseInt(args[0]);
			rpcServer.setListenPort(port);
		}
		String transactionSessionManagerStorePath = null;
		if (args.length > 1)
		{
			transactionSessionManagerStorePath = args[1];
		}
		TransactionSessionManagerFactory.init(transactionSessionManagerStorePath);

		TransactionCoordinator transactionCoordinator = new TransactionCoordinator(rpcServer);
		transactionCoordinator.init();
		rpcServer.setHandler(new TransactionCoordinator(rpcServer));

		TransactionIds.init(1);

		GlobalTransactionIds.setIpAddress(Nets.getLocalIp());
		GlobalTransactionIds.setPort(rpcServer.getListenPort());

		rpcServer.init();

		System.exit(0);
	}
}
